import disable from "@/assets/svg/disable.svg";
import { Ionicons } from "@expo/vector-icons";
import { useState } from "react";
import {
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { SvgIcon } from "../ui/SvgIcon";

// 导入图片和LUT文件
import adaptiveIconImg from "../../assets/images/adaptive-icon.png";
import iconImg from "../../assets/images/icon.png";
import partialReactLogoImg from "../../assets/images/partial-react-logo.png";
import reactLogoImg from "../../assets/images/react-logo.png";
import zurichImg from "../../assets/zurich.jpg";

interface FilterItem {
  key: string;
  label: string;
  previewImage: any; // require() 返回的图片资源
  lut?: any; // LUT文件资源路径，可选
  colorMatrix?: number[]; // 色彩矩阵
}

// 根据滤镜标签生成色彩矩阵
const generateColorMatrix = (label: string): number[] => {
  switch (label) {
    case "原图":
      // 恒等矩阵 - 不做任何变换
      return [
        1, 0, 0, 0, 0,    // R
        0, 1, 0, 0, 0,    // G
        0, 0, 1, 0, 0,    // B
        0, 0, 0, 1, 0     // A
      ];

    case "黑白":
      // 黑白滤镜 - 标准的灰度转换矩阵
      return [
        0.299, 0.587, 0.114, 0, 0,    // R
        0.299, 0.587, 0.114, 0, 0,    // G
        0.299, 0.587, 0.114, 0, 0,    // B
        0, 0, 0, 1, 0                 // A
      ];

    case "复古":
      // 复古滤镜 - 增加温暖色调
      return [
        1.2, 0, 0, 0, 0.1,           // R - 增强红色
        0, 1.0, 0, 0, 0.05,          // G - 轻微增强绿色
        0, 0, 0.8, 0, 0,             // B - 减少蓝色
        0, 0, 0, 1, 0                // A
      ];

    case "缄默":
      // 冷色调滤镜
      return [
        0.9, 0, 0, 0, 0,             // R - 减少红色
        0, 1.0, 0, 0, 0,             // G - 保持绿色
        0, 0, 1.2, 0, 0.1,           // B - 增强蓝色
        0, 0, 0, 1, 0                // A
      ];

    case "暗房":
      // 暗房效果 - 增加对比度和暖色调
      return [
        1.3, 0, 0, 0, -0.1,          // R - 高对比度
        0, 1.2, 0, 0, -0.05,         // G
        0, 0, 0.9, 0, 0,             // B - 减少蓝色
        0, 0, 0, 1, 0                // A
      ];

    case "线条":
      // 高对比度效果
      return [
        1.5, 0, 0, 0, -0.2,          // R - 极高对比度
        0, 1.5, 0, 0, -0.2,          // G
        0, 0, 1.5, 0, -0.2,          // B
        0, 0, 0, 1, 0                // A
      ];

    case "午后":
      // 温暖午后阳光效果
      return [
        1.1, 0.1, 0, 0, 0.05,        // R - 增强红色和一点绿色
        0.05, 1.0, 0.05, 0, 0.02,    // G - 轻微增强
        0, 0, 0.9, 0, 0,             // B - 减少蓝色
        0, 0, 0, 1, 0                // A
      ];

    case "凌晨":
      // 清晨冷色调效果
      return [
        0.8, 0, 0.1, 0, 0,           // R - 减少红色，增加一点蓝色
        0, 0.9, 0.1, 0, 0,           // G - 轻微减少绿色，增加蓝色
        0.1, 0.1, 1.2, 0, 0.05,      // B - 增强蓝色
        0, 0, 0, 1, 0                // A
      ];

    case "胶片":
      // 胶片效果 - 略微降低对比度，增加颗粒感
      return [
        0.95, 0.05, 0, 0, 0.02,      // R
        0.02, 0.9, 0.02, 0, 0.01,    // G
        0, 0.05, 0.95, 0, 0,         // B
        0, 0, 0, 1, 0                // A
      ];

    default:
      // 如果没有匹配的标签，返回恒等矩阵
      return [
        1, 0, 0, 0, 0,
        0, 1, 0, 0, 0,
        0, 0, 1, 0, 0,
        0, 0, 0, 1, 0
      ];
  }
};

interface FilterEditorProps {
  onFilterSelect?: (filter: FilterItem) => void;
  onClear?: () => void;
  onClose?: () => void; // 禁用/关闭按钮事件
  currentImage?: string; // 当前编辑的图片路径
  selectedFilter?: string; // 当前选中的滤镜key
}

// 分类标签数据 - 只包含可通过颜色矩阵实现的滤镜分类
const CATEGORIES = [
  { id: "all", name: "全部" },
  { id: "basic", name: "基础" },
  { id: "vintage", name: "复古" },
  { id: "mood", name: "情调" },
  { id: "artistic", name: "艺术" },
];

// 预览图片数组
const PREVIEW_IMAGES = [
  zurichImg,
  reactLogoImg,
  iconImg,
  adaptiveIconImg,
  partialReactLogoImg,
];

// LUT文件资源
const LUT_FILES = {
  appleLogToRec709: 88,
  appleLogToRec709Fix: 777,
};

// 不同分类的滤镜数据
const FILTER_CATEGORIES: Record<string, FilterItem[]> = {
  all: [
    { key: "original", label: "原图", previewImage: PREVIEW_IMAGES[0] },
    { key: "silent", label: "缄默", previewImage: PREVIEW_IMAGES[1], lut: LUT_FILES.appleLogToRec709 },
    { key: "monochrome", label: "黑白", previewImage: PREVIEW_IMAGES[2] },
    { key: "lines", label: "线条", previewImage: PREVIEW_IMAGES[3] },
    { key: "mountains", label: "群山之后", previewImage: PREVIEW_IMAGES[4] },
    { key: "darkroom", label: "暗房", previewImage: PREVIEW_IMAGES[0], lut: LUT_FILES.appleLogToRec709Fix },
    { key: "vintage", label: "复古", previewImage: PREVIEW_IMAGES[1] },
    { key: "portrait", label: "人像", previewImage: PREVIEW_IMAGES[2] },
    { key: "landscape", label: "风景", previewImage: PREVIEW_IMAGES[3] },
    { key: "street", label: "街拍", previewImage: PREVIEW_IMAGES[4] },
    { key: "film", label: "胶片", previewImage: PREVIEW_IMAGES[0] },
    { key: "art", label: "艺术", previewImage: PREVIEW_IMAGES[1] },
  ],
  popular: [
    { key: "silent", label: "缄默", previewImage: PREVIEW_IMAGES[1], lut: LUT_FILES.appleLogToRec709 },
    { key: "vintage", label: "复古", previewImage: PREVIEW_IMAGES[2] },
    { key: "portrait", label: "人像", previewImage: PREVIEW_IMAGES[3] },
    { key: "film", label: "胶片", previewImage: PREVIEW_IMAGES[4] },
    { key: "art", label: "艺术", previewImage: PREVIEW_IMAGES[0] },
  ],
  monochrome: [
    { key: "monochrome", label: "黑白", previewImage: PREVIEW_IMAGES[1] },
    { key: "darkroom", label: "暗房", previewImage: PREVIEW_IMAGES[2], lut: LUT_FILES.appleLogToRec709Fix },
    { key: "classic_bw", label: "经典黑白", previewImage: PREVIEW_IMAGES[3] },
    { key: "noir", label: "黑色电影", previewImage: PREVIEW_IMAGES[4] },
  ],
  lines: [
    { key: "lines", label: "线条", previewImage: PREVIEW_IMAGES[0] },
    { key: "sketch", label: "素描", previewImage: PREVIEW_IMAGES[1] },
    { key: "outline", label: "轮廓", previewImage: PREVIEW_IMAGES[2] },
  ],
  mountains: [
    { key: "mountains", label: "群山之后", previewImage: PREVIEW_IMAGES[3] },
    { key: "landscape", label: "风景", previewImage: PREVIEW_IMAGES[4] },
    { key: "nature", label: "自然", previewImage: PREVIEW_IMAGES[0] },
  ],
  darkroom: [
    { key: "darkroom", label: "暗房", previewImage: PREVIEW_IMAGES[1], lut: LUT_FILES.appleLogToRec709Fix },
    { key: "vintage", label: "复古", previewImage: PREVIEW_IMAGES[2] },
    { key: "sepia", label: "棕褐色", previewImage: PREVIEW_IMAGES[3] },
  ],
};

/**
 * 滤镜编辑器组件
 * 提供多种滤镜效果选择，支持点击应用滤镜
 */
export default function FilterEditor({
  onFilterSelect,
  onClear,
  onClose,
  currentImage,
  selectedFilter = "original",
}: FilterEditorProps) {
  const [selectedCategory, setSelectedCategory] = useState<string>("all");

  /**
   * 获取当前分类的滤镜列表
   */
  const getCurrentFilters = () => {
    return FILTER_CATEGORIES[selectedCategory] || FILTER_CATEGORIES.all;
  };

  /**
   * 处理分类选择
   */
  const handleCategorySelect = (categoryId: string) => {
    setSelectedCategory(categoryId);
    // 切换分类时重置选中的滤镜为第一个
    const newFilters = FILTER_CATEGORIES[categoryId] || FILTER_CATEGORIES.all;
    if (newFilters.length > 0) {
      onFilterSelect?.(newFilters[0]);
    }
  };

  /**
   * 处理滤镜选择
   */
  const handleFilterSelect = (filter: FilterItem) => {
    // 生成色彩矩阵并添加到滤镜对象中
    const filterWithMatrix = {
      ...filter,
      colorMatrix: generateColorMatrix(filter.label)
    };
    console.log(`FilterEditor: 选择滤镜 "${filter.label}", 生成色彩矩阵:`, filterWithMatrix.colorMatrix);
    onFilterSelect?.(filterWithMatrix);
  };

  /**
   * 处理关闭按钮
   */
  const handleClose = () => {
    onClose?.();
  };

  return (
    <View style={styles.container}>
      {/* 统一的顶部标签栏 */}
      <View style={styles.topToolbar}>
        <TouchableOpacity style={styles.toolButton} onPress={handleClose}>
          <SvgIcon Icon={disable} size={20} color="#222" />
        </TouchableOpacity>

        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.middleButtons}
          contentContainerStyle={styles.middleButtonsContent}
        >
          {CATEGORIES.map((category) => (
            <TouchableOpacity
              key={category.id}
              style={styles.categoryItem}
              onPress={() => handleCategorySelect(category.id)}
            >
              <Text
                style={[
                  styles.categoryText,
                  selectedCategory === category.id &&
                    styles.categoryTextSelected,
                ]}
              >
                {category.name}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      {/* 滤镜横向列表 */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={styles.filterList}
        contentContainerStyle={styles.filterListContainer}
      >
        {getCurrentFilters().map((filter, index) => (
          <TouchableOpacity
            key={filter.key}
            style={styles.filterItem}
            onPress={() => handleFilterSelect(filter)}
          >
            <View style={styles.filterPreview}>
              <Image
                source={filter.previewImage}
                style={styles.filterPreviewImage}
              />
              {selectedFilter === filter.key && (
                <>
                  <View style={styles.overlay} />
                  <View style={styles.checkmark}>
                    <Ionicons name="checkmark" size={24} color="#fff" />
                  </View>
                </>
              )}
            </View>
            <Text style={styles.filterLabel}>{filter.label}</Text>
          </TouchableOpacity>
        ))}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
  },

  // 顶部工具栏样式
  topToolbar: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    backgroundColor: "#fff",
  },
  middleButtons: {
    flex: 1,
  },
  middleButtonsContent: {
    alignItems: "center",
  },
  toolButton: {
    marginRight: 16,
    paddingHorizontal: 4,
  },
  categoryItem: {
    paddingHorizontal: 0,
    paddingVertical: 16,
    marginRight: 24,
  },
  categoryText: {
    fontSize: 14,
    color: "#999",
    fontWeight: "400",
  },
  categoryTextSelected: {
    color: "#000",
    fontWeight: "500",
  },

  // 滤镜横向列表样式
  filterList: {
    backgroundColor: "#fff",
  },
  filterListContainer: {
    paddingHorizontal: 10,
    flexDirection: "row",
  },
  filterItem: {
    alignItems: "center",
    marginRight: 10,
  },
  filterPreview: {
    width: 60,
    height: 60,
    borderRadius: 4,
    overflow: "hidden",
    marginBottom: 8,
    backgroundColor: "#f0f0f0",
    position: "relative",
  },
  overlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0, 0, 0, 0.3)",
    borderRadius: 8,
  },
  filterPreviewImage: {
    width: "100%",
    height: "100%",
    resizeMode: "cover",
  },

  checkmark: {
    position: "absolute",
    top: "50%",
    left: "50%",
    marginTop: -12,
    marginLeft: -12,
  },
  filterLabel: {
    fontSize: 12,
    color: "#333",
    textAlign: "center",
    fontWeight: "400",
  },
});
